#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "wifiiot_gpio.h"

#include "button.h"

WifiIotGpioValue F1_PIN;
WifiIotGpioValue F2_PIN;

unsigned char getButtonState(WifiIotGpioIdx id, WifiIotGpioValue *val)
{
    GpioGetInputVal(id,val);
    return *val;
}

int mode=1;

int buttonMode(void){
    return mode;
}


void buttonInit(void)
{
    GpioInit();
    //初始化LED灯
    IoSetFunc(WIFI_IOT_IO_NAME_GPIO_2, WIFI_IOT_IO_FUNC_GPIO_2_GPIO);

    GpioSetDir(WIFI_IOT_IO_NAME_GPIO_2, WIFI_IOT_GPIO_DIR_OUT);

    //初始化F1按键，设置为下降沿触发中断
    IoSetFunc(WIFI_IOT_IO_NAME_GPIO_11, WIFI_IOT_IO_FUNC_GPIO_11_GPIO);
    GpioSetDir(WIFI_IOT_IO_NAME_GPIO_11, WIFI_IOT_GPIO_DIR_IN);
    IoSetPull(WIFI_IOT_IO_NAME_GPIO_11, WIFI_IOT_IO_PULL_UP);
    
    //初始化F2按键
    IoSetFunc(WIFI_IOT_IO_NAME_GPIO_12, WIFI_IOT_IO_FUNC_GPIO_12_GPIO);
    GpioSetDir(WIFI_IOT_IO_NAME_GPIO_12, WIFI_IOT_GPIO_DIR_IN);
    IoSetPull(WIFI_IOT_IO_NAME_GPIO_12, WIFI_IOT_IO_PULL_UP);

}

void buttonTestTask(void* arg)
{
    (void) arg; 
    buttonInit();
    unsigned char lastF1State = 1; // 假设初始状态为未按下
    unsigned char lastF2State = 1; // 假设初始状态为未按下
    while(1)
    {
        unsigned char F1_State=getButtonState(F1,&F1_PIN);
        unsigned char F2_State=getButtonState(F2,&F2_PIN);

        // 去抖动逻辑
        if (F1_State != lastF1State) {
            osDelay(50); // 简单的去抖动延时
            F1_State = getButtonState(F1,&F1_PIN); // 再次读取状态
        }
        if (F2_State != lastF2State) {
            osDelay(50); // 简单的去抖动延时
            F2_State = getButtonState(F2,&F2_PIN); // 再次读取状态
        }

        // 更新last状态
        lastF1State = F1_State;
        lastF2State = F2_State;

        // 按键逻辑处理
        if (!(F1_State)) {
            mode = 1;
            GpioSetOutputVal(WIFI_IOT_IO_NAME_GPIO_2, 1);
        } else if (!(F2_State)) {
            mode = 0;
            GpioSetOutputVal(WIFI_IOT_IO_NAME_GPIO_2, 0);
        }
        osDelay(100); // 主循环延时
    }
}
void setButtonMode(int m)
{
    mode=m;
}
void buttonThread(void)
{
    osThreadAttr_t attr;
    attr.name = "ButtonTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024;
    attr.priority = osPriorityNormal1;
    if (osThreadNew(buttonTestTask, NULL, &attr) == NULL) {  
        printf("Falied to create ButtonTestTask!\n");
    }
    
}

APP_FEATURE_INIT(buttonThread);
